<template>
  <div class="g-page-container">
    <PageHeader title="商机跟进" />
    <div class="g-content-container">
      <SearchForm ref="search-form" @search="getList(1)" @export="exportList" />
      <ButtonGroup :options="buttons" @click="handleButtonClick" />
      <TableList
        :scroll="{ x: '100%', y: 'calc(100vh - 400px)' }"
        :pagination="paginationMixin"
        :loading="loading"
        :data-source="dataSource"
        :row-selection="rowSelectionMixin"
        @change="handleTableChange"
        @number-click="handleNumberClick"
      />
    </div>

    <component
      :is="currentComponent"
      :visible.sync="visibleDrawer"
      :current-node="currentNode"
      :detail="detail"
      :plan-id="planId"
      :click-info="clickInfo"
      @number-click="clickInfo"
      @fresh="getList"
      @value="getEdit"
    />
    <DialogTransferClue
      :visible.sync="visibleModal"
      :plan-id="planId"
      number="商机编号"
      type="business"
      :selecteds="selectedInfos"
      @fresh="getList"
    />
    <DrawerDeatil
      :visible.sync="visibleDetail"
      :detail="detail"
      :plan-id="planId"
      :process-id="processId"
      :click-info="clickInfo"
    />
  </div>
</template>

<script>
import ButtonGroup from '@/components/button/ButtonGroup.vue';
import mixinTable from '@/mixins/mixin-table.js';
import {
  postBusinessList,
  getBusinessDetail,
  postDeleteBusiness,
  postBusinessBizSnapshoot,
} from '@/api/business.js';
import { getClueFollowDetails } from '@/api/clue';
import { downloadFile } from '@/utils/index.js';
import SearchForm from './components/SearchForm.vue';
import TableList from './components/TableList.vue';
import DialogTransferClue from '@/components/dialog/DialogTransferClue.vue';
import { BUSINESS_NODE } from '@/constants/index';

import DrawerBusinessAdd from './components/DrawerBusinessAdd.vue';
import DrawerBusinessEdit from './components/DrawerBusinessEdit.vue';
import DrawerBusinessDecision from './components/DrawerBusinessDecision.vue';
import DrawerBusinessSubmit from './components/DrawerBusinessSubmit.vue';
import DrawerBusinessBid from './components/DrawerBusinessBid.vue';
import DrawerBusinessProject from './components/DrawerBusinessProject.vue';
import DrawerBusinessResearch from './components/DrawerBusinessResearch.vue';
import DrawerBusinessVerify from './components/DrawerBusinessVerify.vue';
import DrawerBusinessOrder from './components/DrawerBusinessOrder.vue';
import DrawerBusinessDetaile from './components/DrawerBusinessDetaile.vue';
import DrawerDeatil from './components/DrawerDetail.vue';
export default {
  components: {
    ButtonGroup,
    SearchForm,
    TableList,
    DialogTransferClue,
    DrawerBusinessAdd,
    DrawerBusinessEdit,
    DrawerBusinessSubmit,
    DrawerBusinessDecision,
    DrawerBusinessBid,
    DrawerBusinessProject,
    DrawerBusinessResearch,
    DrawerBusinessVerify,
    DrawerBusinessOrder,
    DrawerBusinessDetaile,
    DrawerDeatil,
  },
  mixins: [mixinTable],
  data() {
    return {
      selectedInfos: [],
      columnKey: '',
      visibleModal: false,
      visibleDrawer: false,
      visibleDetail: false,
      currentComponent: 'DrawerBusinessAdd',
      detail: {},
      planId: undefined,
      asc: true,
      currentNode: BUSINESS_NODE[1],
    };
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      if (to.query?.leadsNo || to.query?.type === 'routerAdd') {
        vm.addCallback(to.query);
      } else if (to.query?.opportunityNo) {
        vm.handleNumberClick(to.query, true);
      }
    });
  },
  computed: {
    buttons() {
      const disabled = !this.rowSelectionMixin.selectedRowKeys.length;
      return [
        {
          key: 'add',
          type: 'primary',
          label: '新增商机',
          authKey: 'business-follow-button-add',
          icon: 'plus',
        },
        {
          key: 'delete',
          label: '删除',
          icon: 'delete',
          authKey: 'business-follow-button-delete',
          disabled,
        },
        {
          key: 'retweet',
          label: '转他人处理',
          authKey: 'business-follow-button-retweet',
          icon: 'retweet',
          disabled,
        },
      ];
    },
  },
  watch: {
    visibleModal: {
      handler(val) {
        if (!val) {
          this.rowSelectionMixin.selectedRowKeys = [];
        }
      },
    },
  },
  created() {
    this.getList();
  },

  methods: {
    getSearchForm() {
      const form = this.$refs['search-form']?.form || {};
      const page = {
        current: this.paginationMixin.current,
        pageSize: this.paginationMixin.pageSize,
        asc: this.asc,
        column: this.columnKey,
      };
      return { ...form, ...page };
    },
    async getList(val) {
      if (val) {
        this.paginationMixin.current = 1;
      }
      const form = this.getSearchForm();
      this.loading = true;
      const result = await postBusinessList(form).finally(
        () => (this.loading = false)
      );
      this.paginationMixin.total = result.data.data?.total;
      this.dataSource = result.data.data?.records;
    },
    // 导出
    async exportList() {
      const form = this.$refs['search-form']?.form || {};
      const res = await postBusinessBizSnapshoot({
        asc: this.asc,
        column: this.columnKey,
        ...form,
      });
      await downloadFile(res.data, '商机信息.xlsx');
    },
    handleButtonClick(key) {
      const fn = `${key}Callback`;
      this[fn] && this[fn]();
    },
    // 转他人处理
    async retweetCallback() {
      const selectedInfos = this.rowSelectionMixin.selectedRows
        .filter(item => item.state === '2')
        .map((item, i) => {
          return {
            serialNumber: item.opportunityNo,
            currentUserId: item.handleUserId,
            planId: item.id,
          };
        });
      if (!selectedInfos.length) {
        this.$message.info(
          `仅可转跟进中的数据，现有 ${selectedInfos.length} 条！`
        );
        return;
      }
      try {
        await this.$confirm(
          `仅可转跟进中的数据，共 ${selectedInfos.length} 条，是否确认？`
        );
        this.visibleModal = true;
        this.selectedInfos = selectedInfos;
      } catch (error) {
        // console.log('error: ', error);
      }
    },
    async addCallback(query) {
      const val = query || {};
      this.currentComponent = 'DrawerBusinessAdd';
      if (val.leadsNo) {
        const res = await getClueFollowDetails(query.leadsNo);
        this.detail = res.data.data;
      } else if (val.customerName) {
        this.detail = {
          customerCode: val.customerNo, // 客户编码
          customerName: val.customerName, // 客户名称
          customerShortName: val.name, // 客户简称
          type: val.type,
        };
      } else {
        this.detail = {};
        this.planId = undefined;
      }
      this.currentNode = BUSINESS_NODE[1];
      this.visibleDrawer = true;
    },
    async deleteCallback() {
      const selectedRowKeys = this.rowSelectionMixin.selectedRowKeys || [];
      const checkedRows = this.dataSource.reduce((pre, cur) => {
        if (selectedRowKeys.includes(cur.id)) {
          pre.push(cur);
        }
        return pre;
      }, []);
      const ids = checkedRows
        .filter(item => item.stage === '0')
        .map(item => item.id);
      if (!ids.length) {
        this.$message.info(
          `仅可删除商机信息跟进阶段的数据，现有 ${ids.length} 条！`
        );
        return;
      }
      try {
        await this.$confirm(
          `仅可删除商机信息跟进阶段的数据，共 ${ids.length} 条，是否确认？`
        );
        await postDeleteBusiness(ids);
        this.$message.success('删除成功');
        this.rowSelectionMixin.selectedRowKeys = [];
        this.getList();
      } catch (error) {
        console.log('error: ', error);
      }
    },
    async handleNumberClick(record, isDetail) {
      if (record.path) {
        let currentNode = BUSINESS_NODE[Number(record.stage)];
        if (!currentNode) {
          this.$message.error('非有效节点，无法进入！');
          return;
        }
        this.currentNode = BUSINESS_NODE[Number(record.stage)];
        this.currentComponent = `Drawer${this.currentNode.key}`;
      } else {
        this.currentNode = BUSINESS_NODE[Number(record.stage)];
        if (!this.currentNode && !isDetail) {
          this.$message.error('非有效节点，无法进入！');
          return;
        }
        if (record.isCurrentProcessor && record.transferStatus !== '1') {
          this.currentComponent = `Drawer${this.currentNode.key}`;
        } else {
          this.currentComponent = 'DrawerBusinessDetaile';
        }
      }
      const result = await getBusinessDetail(record.opportunityNo);
      this.detail = result.data.data;
      this.planId = this.detail.id;
      this.visibleDrawer = true;
    },
    // 进编辑商机页
    getEdit() {
      this.visibleDrawer = false;
      this.currentComponent = 'DrawerBusinessEdit';
      this.visibleDrawer = true;
    },
    handleTableChange(page, filters, sorter, { currentDataSource }) {
      this.asc = sorter.order === 'ascend' ? true : false;
      this.columnKey = sorter.columnKey;
      this.paginationMixin = page;
      this.getList();
    },
    clickInfo(val) {
      this.detail = val;
      this.planId = val.id;
      this.processId = val.processId;
      this.visibleDetail = true;
    },
  },
};
</script>
